<template>
	<view class="content">
		<view class="box"
			:style='{ "width": "100%", "padding": "0 40rpx", "alignItems": "center", "background": "url(http://codegen.caihongy.cn/20250208/663f8e6fd10444f08c8ffd7a9da52baf.png) no-repeat center top / 100% auto", "display": "flex", "height": "100%" }'>
			<view
				:style='{ "width": "100%", "padding": "0", "position": "relative", "background": "none", "height": "auto" }'>
				<image
					:style='{ "width": "160rpx", "margin": "0 auto 24rpx auto", "borderRadius": "8rpx", "display": "none", "height": "160rpx" }'
					src="http://codegen.caihongy.cn/20201114/7856ba26477849ea828f481fa2773a95.jpg" mode="aspectFill">
				</image>
				<view v-if="loginType == 1"
					:style='{ "border": "none", "width": "100%", "margin": "0 0 40rpx 0", "alignItems": "center", "display": "flex", "height": "auto" }'
					class="uni-form-item uni-column">
					<view
						:style='{ "padding": "0", "color": "#707070", "borderRadius": "0", "textAlign": "center", "background": "none", "flex": "none", "width": "160rpx", "lineHeight": "50rpx", "fontSize": "28rpx", "height": "50rpx" }'
						class="label">账号：</view>
					<input v-model="username"
						:style='{ "border": "none", "padding": "0px 24rpx", "margin": "0px", "borderColor": "#D6D6D6", "color": "rgb(0, 0, 0)", "borderRadius": "0", "flex": "1", "background": "none", "borderWidth": "0 0 2rpx 0 ", "fontSize": "28rpx", "borderStyle": "solid", "height": "80rpx" }'
						type="text" class="uni-input" name="" placeholder="请输入账号" />
				</view>
				<view v-if="loginType == 1"
					:style='{ "border": "none", "width": "100%", "margin": "0 0 40rpx 0", "alignItems": "center", "display": "flex", "height": "auto" }'
					class="uni-form-item uni-column">
					<view
						:style='{ "padding": "0", "color": "#707070", "borderRadius": "0", "textAlign": "center", "background": "none", "flex": "none", "width": "160rpx", "lineHeight": "50rpx", "fontSize": "28rpx", "height": "50rpx" }'
						class="label">密码：</view>
					<input v-model="password"
						:style='{ "border": "none", "padding": "0px 24rpx", "margin": "0px", "borderColor": "#D6D6D6", "color": "rgb(0, 0, 0)", "borderRadius": "0", "flex": "1", "background": "none", "borderWidth": "0 0 2rpx 0 ", "fontSize": "28rpx", "borderStyle": "solid", "height": "80rpx" }'
						type="password" class="uni-input" name="" placeholder="请输入密码" />
				</view>
				
				<!-- 登录提示 -->
	<!-- 			<view class="login-tips"
					:style='{ "border": "none", "width": "100%", "margin": "0 0 40rpx 0", "color": "#707070", "textAlign": "center", "fontSize": "28rpx", "lineHeight": "40rpx" }'>
					系统将自动识别您的账号类型
				</view> -->

				<button v-if="loginType == 1" class="btn-submit" @tap="onLoginTap" type="primary"
					:style='{ "border": "0", "padding": "0px", "margin": "0 0 24rpx 0", "color": "#fff", "borderRadius": "8rpx", "background": "linear-gradient( 135deg, #9EF0EA 0%, #99ABFF 100%)", "width": "100%", "lineHeight": "80rpx", "fontSize": "32rpx", "fontWeight": "600", "height": "80rpx" }'>登陆</button>
				<button v-if="loginType == 2" class="btn-submit" @tap="onFaceLoginTap" type="primary"
					:style='{ "border": "0", "padding": "0px", "margin": "0 0 24rpx 0", "color": "#fff", "borderRadius": "8rpx", "background": "linear-gradient( 135deg, #9EF0EA 0%, #99ABFF 100%)", "width": "100%", "lineHeight": "80rpx", "fontSize": "32rpx", "fontWeight": "600", "height": "80rpx" }'>人脸识别登录</button>
				<view class="links" style="display: flex;justify-content: space-between;"
					:style='{ "width": "100%", "margin": "0 0 24rpx 0", "flexWrap": "wrap", "display": "flex", "height": "auto" }'>
					<view style="display: flex;justify-content: space-between;">
						<view class="link-highlight" @tap="onRegisterTap('laoren')"
							:style='{ "color": "#6B6153", "padding": "0 8rpx", "fontSize": "28rpx" }'>注册普通账户</view>
						<view class="link-highlight" @tap="onRegisterTap('yuangong')"
							:style='{ "color": "#6B6153", "padding": "0 8rpx", "fontSize": "28rpx" }'>注册服务账户</view>
					</view>

					<view class="link-highlight" @tap="onForgotPassword"
						:style='{ "color": "#6B6153", "padding": "0 8rpx", "fontSize": "28rpx" }'>忘记密码?</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import menu from '@/utils/menu'
export default {
	data() {
		return {
			username: '',
			password: '',
			loginType: 1,
			codes: [{
				num: 1,
				color: '#000',
				rotate: '10deg',
				size: '16px'
			}, {
				num: 2,
				color: '#000',
				rotate: '10deg',
				size: '16px'
			}, {
				num: 3,
				color: '#000',
				rotate: '10deg',
				size: '16px'
			}, {
				num: 4,
				color: '#000',
				rotate: '10deg',
				size: '16px'
			}],
			options: [
				'请选择登录用户类型',
				'老人',
				'员工',
			],
			optionsValues: [
				'',
				'laoren',
				'yuangong',
			],
			index: 0,
			roleNum: 0,
		}
	},
	onLoad() {
		// 不再需要动态加载菜单，保留选项供后续使用
		this.styleChange()
	},
	onShow() {
	},
	mounted() {
	},
	methods: {
		styleChange() {
			this.$nextTick(() => {
				// document.querySelectorAll('.uni-input .uni-input-input').forEach(el=>{
				//   el.style.backgroundColor = this.loginFrom.content.input.backgroundColor
				// })
			})
		},
		onRegisterTap(tableName) {
			uni.setStorageSync("loginTable", tableName);
			this.$utils.jump('../register/register')
		},
		async onLoginTap() {
			if (!this.username) {
				this.$utils.msg('请输入用户名')
				return
			}
			if (!this.password) {
				this.$utils.msg('请输入用户密码')
				return
			}

			this.unifiedLoginPost()
		},
		async unifiedLoginPost() {
			try {
				// 使用新的统一登录接口
				let res = await this.$api.unifiedLogin({
					username: this.username,
					password: this.password
				});
				
				if (!res.token) {
					this.$utils.msg('登录失败，请检查账号密码');
					return;
				}
				
				uni.removeStorageSync("useridTag");
				uni.setStorageSync("appToken", res.token);
				uni.setStorageSync("nickname", this.username);
				
				// 获取用户信息
				let sessionRes = await this.$api.unifiedSession();
				console.log("用户会话信息:", sessionRes);
				
				if (!sessionRes || !sessionRes.data) {
					this.$utils.msg('获取用户信息失败');
					return;
				}
				
				// 从session中确定用户类型和角色
				let userTableName = '';
				let userRole = '';
				
				// 判断用户类型
				if (sessionRes.data.yuangongzhanghao) {
					// 员工用户
					userTableName = 'yuangong';
					userRole = '服务人员';
					console.log("检测到员工账号:", sessionRes.data.yuangongzhanghao);
				} else if (sessionRes.data.zhanghao) {
					// 老人用户
					userTableName = 'laoren';
					userRole = '老人';
					console.log("检测到老人账号:", sessionRes.data.zhanghao);
				} else {
					// 如果无法从session数据判断，尝试使用token信息
					const tokenInfo = this.parseToken(res.token);
					userTableName = tokenInfo.tableName || 'laoren';
					userRole = tokenInfo.role || '老人';
					console.log("从Token获取用户类型:", userTableName, userRole);
				}
				
				console.log("确定的用户类型:", userTableName, "角色:", userRole);
				
				// 保存用户信息
				uni.setStorageSync("nowTable", userTableName);
				uni.setStorageSync("appRole", userRole);
				
				if (sessionRes.data.touxiang) {
					uni.setStorageSync('headportrait', sessionRes.data.touxiang);
				} else if (sessionRes.data.headportrait) {
					uni.setStorageSync('headportrait', sessionRes.data.headportrait);
				}
				uni.setStorageSync('userSession', JSON.stringify(sessionRes.data));
				uni.setStorageSync("appUserid", sessionRes.data.id);
				uni.setStorageSync("appUserzhanghao", sessionRes.data.zhanghao); // 存储账号
				if (sessionRes.data.vip) {
					uni.setStorageSync("vip", sessionRes.data.vip);
				}
				
				// 根据用户表名进行跳转，确保精确判断
				if (userTableName === 'yuangong') {
					console.log("跳转到服务人员页面");
					uni.navigateTo({
						url: '../hashslinger/index'
					});
				} else {
					console.log("跳转到普通用户页面");
					uni.navigateTo({
						url: '../index/index'
					});
				}
			} catch (e) {
				console.error('登录出错:', e);
				this.$utils.msg('登录失败，请检查账号密码');
			}
		},
		// 从token解析用户信息（简单实现，根据实际token格式调整）
		parseToken(token) {
			try {
				// 如果是JWT格式，可以解析payload部分
				const payload = token.split('.')[1];
				if (payload) {
					return JSON.parse(atob(payload));
				}
				
				// 如果不是标准JWT，则通过API获取用户类型
				return { 
					tableName: '',
					role: ''
				};
			} catch (e) {
				console.error('Token解析错误:', e);
				return { 
					tableName: '',
					role: ''
				};
			}
		},
		onForgotPassword() {
			uni.navigateTo({
				url: '../forget/forget'
			})
		}
	}
}
</script>

<style lang="scss" scoped>
page {
	height: 100%;
}

.content {
	height: 100%;
	box-sizing: border-box;
}

.forget-password {
	display: flex;
	justify-content: flex-end;
	margin-top: 20rpx;
	padding-right: 10rpx;
}

.forget-text {
	color: #007AFF;
	font-size: 26rpx;
}

.login-tips {
	background-color: rgba(158, 240, 234, 0.1);
	padding: 20rpx;
	border-radius: 8rpx;
	margin-bottom: 20rpx;
}
</style>
